var xmlreader = require("xmlreader");
var crypto = require('crypto');
var Decimal = require('decimal.js');


class Wxpay {
    //把金额转为分
    getmoney(money: any) {
        return new Decimal(money).mul(new Decimal(100)).toNumber();
    }

    // 随机字符串产生函数  
    createNonceStr() {
        return Math.random().toString(36).substr(2, 15);
    };

    // 时间戳产生函数  
    createTimeStamp() {
        return parseInt(new Date().getTime() / 1000 + '');
    }

    //签名加密算法
    paysignjsapi(appid: any, body: any, mch_id: any, nonce_str: any, notify_url: any, openid: any, out_trade_no: any, spbill_create_ip: any, total_fee: any, trade_type: any, mchkey: any) {
        var ret = {
            appid: appid,
            mch_id: mch_id,
            nonce_str: nonce_str,
            body: body,
            notify_url: notify_url,
            openid: openid,
            out_trade_no: out_trade_no,
            spbill_create_ip: spbill_create_ip,
            total_fee: total_fee,
            trade_type: trade_type
        };
        console.log('ret==', ret);
        var string = this.raw(ret);
        var key = mchkey;
        string = string + '&key=' + key;
        console.log('string=', string);
        return crypto.createHash('MD5').update(string, 'utf8').digest('hex').toUpperCase();
    }
    //签名加密算法,第二次的签名
    paysignjsapifinal(appid: any, mch_id: any, prepayid: any, noncestr: any, timestamp: any, mchkey: any, total_fee?: any) {
        var ret = {
            appId: appid,
            nonceStr: noncestr,
            package: `prepay_id=${prepayid}`,
            signType: 'MD5',
            //partnerid: mch_id,
            //prepayid: prepayid,
            //package: 'Sign=WXPay',
            //noncestr: noncestr,
            timeStamp: timestamp//,
            //total_fee: total_fee
        };
        //console.log('retretret==', ret);
        var string = this.raw(ret);
        var key = mchkey;
        string = string + '&key=' + key;
        console.log('二次签名=', string);
        return crypto.createHash('MD5').update(string, 'utf8').digest('hex').toUpperCase();
    }
    getXMLNodeValue(xml: any) {
        // var tmp = xml.split("<"+node_name+">");
        // console.log('tmp',tmp);
        // var _tmp = tmp[1].split("</"+node_name+">");
        // console.log('_tmp',_tmp);
        // return _tmp[0];
        xmlreader.read(xml, (errors: any, response: any) => {
            if (null !== errors) {
                console.log(errors)
                return;
            }
            console.log('长度===', response.xml.prepay_id.text().length);
            var prepay_id = response.xml.prepay_id.text();
            console.log('解析后的prepay_id==', prepay_id);
            return prepay_id;
        });
    }
    //签名加密算法
    makesign(ret: any, mchkey: any) {
        var string = this.raw(ret);
        var key = mchkey;
        string = string + '&key=' + key;
        console.log('签名=', string);
        return crypto.createHash('MD5').update(string, 'utf8').digest('hex').toUpperCase();
    }
    raw(args: any) {
        var keys = Object.keys(args);
        keys = keys.sort()
        var newArgs: any = {};
        keys.forEach(function (key) {
            newArgs[key] = args[key];
        });
        var string = '';
        for (var k in newArgs) {
            string += '&' + k + '=' + newArgs[k];
        }
        string = string.substr(1);
        return string;
    }

    json2Xml(json: any) {
        let _xml = '';
        Object.keys(json).map((key) => {
            _xml += `<${key}>${json[key]}</${key}>`
        })
        return `<xml>${_xml}</xml>`;
    }

}

export const wxpay = new Wxpay();